package com.indi.gulimall.order.listener;

import com.indi.common.constant.OrderConstant;
import com.indi.common.dto.mq.SeckillSkuDTO;
import com.indi.gulimall.order.config.AlipayTemplate;
import com.indi.gulimall.order.entity.OrderEntity;
import com.indi.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author UnityAlvin
 * @date 2021/7/24 10:52
 */
@RabbitListener(queues = OrderConstant.ORDER_RELEASE_ORDER_QUEUE)
@Service
public class OrderCloseListener {
    @Resource
    private OrderService orderService;

    @Resource
    private AlipayTemplate alipayTemplate;

    @RabbitHandler
    public void handleOrderClose(OrderEntity order, Message message, Channel channel) throws IOException {
        System.out.println("收到过期订单的消息");

        try {

            orderService.closeOrder(order);
            // TODO 避免因为网络问题、或者用户正在支付中导致的订单与时间冲突问题，手动调用支付宝收单
            // 可能因为内网穿透的问题，提示订单不存在，关单失败，先保留
//            String result = alipayTemplate.closePay(order.getOrderSn());
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    @RabbitHandler
    public void handleSeckillOrderClose(SeckillSkuDTO seckillSkuDTO, Message message, Channel channel) throws IOException {
        System.out.println("收到过期秒杀订单的消息");

        try {

            orderService.closeSeckillOrder(seckillSkuDTO);
            // TODO 避免因为网络问题、或者用户正在支付中导致的订单与时间冲突问题，手动调用支付宝收单
            // 可能因为内网穿透的问题，提示订单不存在，关单失败，先保留
//            String result = alipayTemplate.closePay(order.getOrderSn());
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
